package com.zrf.base.knowledge.concurrent.demo;

import com.google.common.collect.Maps;

import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @date 2020/3/24
 * @AUTHER zhouruifeng
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        Cache cache = new Cache();

        for (int i = 0; i < 5; i++) {
            int tmp = i;
            new Thread(()->{
                cache.put(String.valueOf(tmp), tmp);
            }, "write-" + String.valueOf(i)).start();
        }

        for (int i = 0; i < 5; i++) {
            int tmp = i;
            new Thread(()->{
                cache.get(String.valueOf(tmp));
            }, "read-" + String.valueOf(i)).start();
        }
    }
}

class Cache {
    private volatile Map<String, Object> map = Maps.newHashMap();

    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock(false);

    private Lock writeLock = readWriteLock.writeLock();

    private Lock readLock = readWriteLock.readLock();

    public void put(String key, Object value) {
        try {
            System.out.println(Thread.currentThread().getName() + " try lock ");
            writeLock.lockInterruptibly();
            System.out.println(Thread.currentThread().getName() + " start put " + key + ",value: " + value);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + " end put " + key + ",value: " + value);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            writeLock.unlock();
        }


    }

    public Object get(String key) {
        try {
            System.out.println(Thread.currentThread().getName() + " try lock ");
            readLock.lockInterruptibly();
            System.out.println(Thread.currentThread().getName() + " end get " + key + ",value: " + map.get(key).toString());
            return map.get(key);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return null;
        } finally {
            readLock.unlock();
        }
    }
}